package com.example.pei.ithinklearnt.view.activity;

import android.Manifest;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.view.base.BaseActivity;

import butterknife.BindView;
import butterknife.OnClick;
import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

import static com.example.pei.ithinklearnt.utils.MyUtils.checkPassword;
import static com.example.pei.ithinklearnt.utils.MyUtils.isAllSpace;
import static com.example.pei.ithinklearnt.utils.PermisionUtil.hasReadPhoneStatePermission;
import static com.example.pei.ithinklearnt.utils.ToastUtil.ToastShow;

public class ForgetPassWordActivity extends BaseActivity {

    //@BindView(R.id.et_phone)
    //EditText etPhone;
    @BindView(R.id.btn_confirm)
    Button btnConfirm;
    @BindView(R.id.btn_sendCode)
    Button btnSendCode;
    @BindView(R.id.ed_code)
    EditText edCode;
    @BindView(R.id.et_passwd)
    EditText etPassWd;
    @BindView(R.id.tv_phone)
    TextView tvPhone;

    private int i=0;
    private static final int RC_READ_PHONE_STATE_PERM = 124;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password);
        initUI();
    }

    @OnClick(R.id.btn_back)
    void back(){
        finish();
    }

    @OnClick(R.id.btn_sendCode)
    @AfterPermissionGranted(RC_READ_PHONE_STATE_PERM)
    public void readPhoneStateTask() {
        if (hasReadPhoneStatePermission(this)) {
            //如果有权限
            sendVerifyCode();  //发送验证码
        } else {
            // Ask for both permissions
            EasyPermissions.requestPermissions(
                    this,
                    "需要你的手机号否则将无法接收到验证码.",
                    RC_READ_PHONE_STATE_PERM,
                    Manifest.permission.READ_PHONE_STATE);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (hasReadPhoneStatePermission(this)) {
            //如果有权限
            sendVerifyCode();  //发送验证码
        }
        // EasyPermissions handles the request result.
        //EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }



    //确认修改
    @OnClick(R.id.btn_confirm)
    void forgetPassWord(){
        btnConfirm.setClickable(false);

        if(edCode.getText().toString().equals("")){
            toast("请输入验证码");
            btnConfirm.setClickable(true);
            return;
        }
        if(!checkPassword(etPassWd.getText().toString())){
            toast("密码不符合要求");
            btnConfirm.setClickable(true);
            return;
        }

        BmobUser.resetPasswordBySMSCode(edCode.getText().toString(),
                etPassWd.getText().toString(), new UpdateListener() {
            @Override
            public void done(BmobException ex) {
                btnConfirm.setClickable(true);
                if(ex==null){
                    //Log.i("smile", "密码重置成功");
                    toast("重置成功(￣▽￣)~*");
                    finish();
                }else{
                    if(ex.getErrorCode()==207){
                        toast("验证码错误(；д；)");
                    }else
                        toast("重置失败：code ="+ex.getErrorCode()+",msg = "+ex.getLocalizedMessage());
                }
            }
        });
    }

    //发送验证码

    void sendVerifyCode(){
        changeBtnGetCode();
        BmobSMS.requestSMSCode(this,AppApplication.getCurrentUser().getMobilePhoneNumber() , "交友神器",new RequestSMSCodeListener() {
            @Override
            public void done(Integer smsId, cn.bmob.sms.exception.BmobException e) {
                if (e == null) {
                    //验证码发送成功
                    ToastShow(ForgetPassWordActivity.this,"正在发送,请稍后...",0);
                }else if(e.getErrorCode()==10010){
                    toast("该手机号发送短信达到限制，请等待一段时间");
                }
                else{
                    ToastShow(ForgetPassWordActivity.this,"发送失败 Code:"+e.getMessage(),0);
                }
            }
        });
    }


    private void initUI(){
        //178 2661 6891
        if(AppApplication.getCurrentUser().getMobilePhoneNumber()==null||AppApplication.getCurrentUser().getMobilePhoneNumber().equals(""))
        {
            toast("您不需要修改密码哦~~~");
            finish();
        }
        String phone=AppApplication.getCurrentUser().getMobilePhoneNumber();
        String content="您的手机号码是"+phone.charAt(0)+phone.charAt(1)+phone.charAt(2)+
                "****"+phone.charAt(7)+phone.charAt(8)+phone.charAt(9)+phone.charAt(10)+
                ",点击\"获取验证码\":";
        tvPhone.setText(content);
    }

    //每次验证请求需要间隔35S
    private int time=60;
    //控制按钮样式是否改变
    private boolean tag = true;

    public void changeBtnGetCode() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                if (tag) {
                    while (time > 0) {
                        time--;
                        setWaitSendAgain(time);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    tag = false;
                }
                time = 60;
                tag = true;


                setCanSendAgain();

            }
        };
        thread.start();
    }


    private void setWaitSendAgain(final int time) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btnSendCode.setText(getResources().getString(R.string.sendagain,time));
                btnSendCode.setClickable(false);
                btnSendCode.setTextColor(Color.parseColor("#a6a6a6"));
            }
        });
    }


    private void setCanSendAgain() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btnSendCode.setText("重新发送");
                btnSendCode.setClickable(true);
                btnSendCode.setTextColor(Color.parseColor("#808080"));
            }
        });

    }

}
